package com.github.tvbox.osc.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.github.tvbox.osc.R;
import com.github.tvbox.osc.base.App;
import com.github.tvbox.osc.base.BaseLazyFragment;
import com.github.tvbox.osc.bean.Movie;
import com.github.tvbox.osc.event.ServerEvent;
import com.github.tvbox.osc.imloader.ImageNetAdapter;
import com.github.tvbox.osc.picasso.RoundTransformation;
import com.github.tvbox.osc.ui.activity.AppsActivity;
import com.github.tvbox.osc.ui.activity.CollectActivity;
import com.github.tvbox.osc.ui.activity.DriveActivity;
import com.github.tvbox.osc.ui.activity.HistoryActivity;
import com.github.tvbox.osc.ui.activity.LivePlayActivity;
import com.github.tvbox.osc.ui.activity.PushActivity;
import com.github.tvbox.osc.ui.activity.SearchActivity;
import com.github.tvbox.osc.ui.activity.SettingActivity;
import com.github.tvbox.osc.ui.tv.widget.BannerViewPage;
import com.github.tvbox.osc.ui.tv.widget.RCImageView;
import com.github.tvbox.osc.util.DefaultConfig;
import com.github.tvbox.osc.util.FastClickCheckUtil;
import com.github.tvbox.osc.util.HawkConfig;
import com.github.tvbox.osc.util.MD5;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.listener.OnPageChangeListener;
import com.youth.banner.util.BannerUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.autosize.utils.AutoSizeUtils;

/**
 * @author pj567
 * @date :2021/3/9
 * @description:
 */
public class UserFragment extends BaseLazyFragment implements View.OnClickListener {
    private LinearLayout tvDrive;
    private LinearLayout tvLive;
    private LinearLayout tvSearch;
    private LinearLayout tvSetting;
    private LinearLayout tvHistory;
    private LinearLayout tvCollect;
    private LinearLayout tvPush;

    private LinearLayout appLL;

//    private ImageView hotUp;
//
//    private ImageView hotDown;

    private RCImageView ivHot;

//    private Banner banner;

    private List<Movie.Video> homeSourceRec;

    private List<Movie.Video> movieHotList;

    private int hotPosition = 0;

    public static UserFragment newInstance() {
        return new UserFragment();
    }

    public static UserFragment newInstance(List<Movie.Video> recVod) {
        return new UserFragment().setArguments(recVod);
    }

    public UserFragment setArguments(List<Movie.Video> recVod) {
        this.homeSourceRec = recVod;
        return this;
    }

    @Override
    public void onFragmentResume() {
        super.onFragmentResume();
        if (movieHotList != null && movieHotList.size() > 0) {
            handler.postDelayed(mRunnable, 5000);
//            banner.start();
        }
//        wupk 不在获取历史记录
//        if (Hawk.get(HawkConfig.HOME_REC, 0) == 2) {
//            List<VodInfo> allVodRecord = RoomDataManger.getAllVodRecord(20);
//            List<Movie.Video> vodList = new ArrayList<>();
//            for (VodInfo vodInfo : allVodRecord) {
//                Movie.Video vod = new Movie.Video();
//                vod.id = vodInfo.id;
//                vod.sourceKey = vodInfo.sourceKey;
//                vod.name = vodInfo.name;
//                vod.pic = vodInfo.pic;
//                if (vodInfo.playNote != null && !vodInfo.playNote.isEmpty())
//                    vod.note = "上次看到" + vodInfo.playNote;
//                vodList.add(vod);
//            }
//            userHotVodAdapter.setNewData(vodList);
//        }
    }

    @Override
    protected void onFragmentPause() {
        super.onFragmentPause();
        handler.removeCallbacks(mRunnable);
//        banner.stop();
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_user2;
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        tvDrive = findViewById(R.id.tvDrive);
        tvLive = findViewById(R.id.tvLive);
        tvSearch = findViewById(R.id.tvSearch);
        tvSetting = findViewById(R.id.tvSetting);
        tvCollect = findViewById(R.id.tvFavorite);
        tvHistory = findViewById(R.id.tvHistory);
        tvPush = findViewById(R.id.tvPush);
        appLL = findViewById(R.id.appLL);
//        hotUp = findViewById(R.id.hotUp);
//        hotDown = findViewById(R.id.hotDown);
        ivHot = findViewById(R.id.ivHot);
//        banner = findViewById(R.id.banner);

        if (movieHotList == null) {
            movieHotList = new ArrayList<>();
        }
        tvDrive.setOnClickListener(this);
        tvLive.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
        tvSetting.setOnClickListener(this);
        tvHistory.setOnClickListener(this);
        tvPush.setOnClickListener(this);
        tvCollect.setOnClickListener(this);
        appLL.setOnClickListener(this);
//        hotUp.setOnClickListener(this);
//        hotDown.setOnClickListener(this);
        ivHot.setOnClickListener(this);
//        banner.setOnClickListener(this);
        tvDrive.setOnFocusChangeListener(focusChangeListener);
        tvLive.setOnFocusChangeListener(focusChangeListener);
        tvSearch.setOnFocusChangeListener(focusChangeListener);
        tvSetting.setOnFocusChangeListener(focusChangeListener);
        tvHistory.setOnFocusChangeListener(focusChangeListener);
        tvPush.setOnFocusChangeListener(focusChangeListener);
        tvCollect.setOnFocusChangeListener(focusChangeListener);
        appLL.setOnFocusChangeListener(focusChangeListener);
        ivHot.setOnFocusChangeListener(focusChangeListener);
//        banner.setOnFocusChangeListener(focusChangeListener);
        intBannerHttp();
    }

    private final View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus){
                v.animate().scaleX(1.05f).scaleY(1.05f).setDuration(300).setInterpolator(new BounceInterpolator()).start();
                v.bringToFront();
            }else{
                v.animate().scaleX(1.0f).scaleY(1.0f).setDuration(300).setInterpolator(new BounceInterpolator()).start();
            }
        }
    };

    /**
     * 获取热门资源
     */
    private void intBannerHttp() {
        try {
            OkGo.<String>get("https://gitee.com/godoox/turbo/raw/master/hot/hot_v20230511.json").execute(new AbsCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    String netJson = response.body();
                    ArrayList<Movie.Video> list = loadHots(netJson);
                    if (list.size() > 0) {
                        movieHotList.addAll(list);
                        Movie.Video item = list.get(0);
//                        hotUp.setVisibility(View.VISIBLE);
//                        hotDown.setVisibility(View.VISIBLE);
                        App.getInstance().setImagePath(item.pic, ivHot, 620, 340, 15);
                        handler.post(mRunnable);
//                        showBanner();
                    }
                }

                @Override
                public String convertResponse(okhttp3.Response response) throws Throwable {
                    return response.body().string();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private void showBanner() {
//        banner.setAdapter(new ImageNetAdapter(movieHotList))
//                .setLoopTime(6000)
//                .setOrientation(Banner.VERTICAL)
//                .setIndicator(new CircleIndicator(mContext), false);
//        banner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(Object data, int position) {
//                Intent newIntent = new Intent(mContext, SearchActivity.class);
//                newIntent.putExtra("title", ((Movie.Video)data).name);
//                newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                mActivity.startActivity(newIntent);
//            }
//        });
//    }


    private ArrayList<Movie.Video> loadHots(String json) {
        ArrayList<Movie.Video> result = new ArrayList<>();
        try {
            JsonArray array = new Gson().fromJson(json, JsonArray.class);
            for (JsonElement ele : array) {
                JsonObject obj = (JsonObject) ele;
                Movie.Video vod = new Movie.Video();
                vod.name = obj.get("title").getAsString();
                vod.pic = obj.get("image_url").getAsString();
                result.add(vod);

            }
        } catch (Throwable th) {

        }
        return result;
    }

    @Override
    public void onClick(View v) {
        HawkConfig.hotVodDelete = false;

        FastClickCheckUtil.check(v);
        if (v.getId() == R.id.tvLive) {
            jumpActivity(LivePlayActivity.class);
        } else if (v.getId() == R.id.tvSearch) {
            jumpActivity(SearchActivity.class);
        } else if (v.getId() == R.id.tvSetting) {
            jumpActivity(SettingActivity.class);
        } else if (v.getId() == R.id.tvHistory) {
            jumpActivity(HistoryActivity.class);
        } else if (v.getId() == R.id.tvPush) {
            jumpActivity(PushActivity.class);
        } else if (v.getId() == R.id.tvFavorite) {
            jumpActivity(CollectActivity.class);
        } else if (v.getId() == R.id.tvDrive) {
            jumpActivity(DriveActivity.class);
        } else if (v.getId() == R.id.appLL) {
            jumpActivity(AppsActivity.class);
        }

//        else if (v.getId() == R.id.hotUp) {
//            if (hotPosition == 0) {
//                //数组从0开始,所以要减去一个
//                hotPosition = movieHotList.size() - 1;
//            } else {
//                hotPosition = hotPosition - 1;
//            }
//            Movie.Video video = movieHotList.get(hotPosition);
//            App.getInstance().setImagePath(video.pic, ivHot, 620, 340, 15);
//        } else if (v.getId() == R.id.hotDown) {
//            if (hotPosition + 1 >= movieHotList.size()) {
//                hotPosition = 0;
//            } else {
//                hotPosition = hotPosition + 1;
//            }
//            Movie.Video video = movieHotList.get(hotPosition);
//            App.getInstance().setImagePath(video.pic, ivHot, 620, 340, 15);
//        }

        else if (v.getId() == R.id.ivHot) {
            Movie.Video video = movieHotList.get(hotPosition);
            Intent newIntent = new Intent(mContext, SearchActivity.class);
            newIntent.putExtra("title", video.name);
            newIntent.putExtra("pic", video.pic);
            newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            mActivity.startActivity(newIntent);
        }
    }

    private Handler handler = new Handler(Looper.myLooper());

    private final Runnable mRunnable = new Runnable() {
        @SuppressLint({"DefaultLocale", "SetTextI18n"})
        @Override
        public void run() {
            if (movieHotList.size() > 0) {
                if (hotPosition + 1 >= movieHotList.size()) {
                    hotPosition = 0;
                } else {
                    hotPosition = hotPosition + 1;
                }
                Movie.Video video = movieHotList.get(hotPosition);
                App.getInstance().setImagePath(video.pic, ivHot, 620, 340, 15);
                handler.postDelayed(this, 5000);
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void server(ServerEvent event) {
        if (event.type == ServerEvent.SERVER_CONNECTION) {
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}